import { defineStore } from "pinia";
import { ref } from "vue";
import type { AppConfig, AudioDevices, AudioLevels } from "../types";
import * as tauriApi from "../services/tauri-api";

export const useConfigStore = defineStore("config", () => {
  // State
  const config = ref<AppConfig | null>(null);
  const audioDevices = ref<AudioDevices | null>(null);
  const audioLevels = ref<AudioLevels | null>(null);
  const loading = ref(false);
  const error = ref<string | null>(null);

  // Actions
  const loadConfig = async () => {
    loading.value = true;
    error.value = null;
    
    try {
      config.value = await tauriApi.loadConfig();
    } catch (err) {
      error.value = err instanceof Error ? err.message : "Failed to load config";
      throw err;
    } finally {
      loading.value = false;
    }
  };

  const saveConfig = async (newConfig: AppConfig) => {
    loading.value = true;
    error.value = null;
    
    try {
      await tauriApi.saveConfig(newConfig);
      config.value = newConfig;
    } catch (err) {
      error.value = err instanceof Error ? err.message : "Failed to save config";
      throw err;
    } finally {
      loading.value = false;
    }
  };

  const loadAudioDevices = async () => {
    loading.value = true;
    error.value = null;
    
    try {
      audioDevices.value = await tauriApi.getAudioDevices();
    } catch (err) {
      error.value = err instanceof Error ? err.message : "Failed to load audio devices";
      throw err;
    } finally {
      loading.value = false;
    }
  };

  const setAudioDevice = async (inputDevice?: string, outputDevice?: string) => {
    loading.value = true;
    error.value = null;
    
    try {
      await tauriApi.setAudioDevice(inputDevice, outputDevice);
      
      // Update current devices in the store
      if (audioDevices.value) {
        if (inputDevice !== undefined) {
          audioDevices.value.current_input = inputDevice;
        }
        if (outputDevice !== undefined) {
          audioDevices.value.current_output = outputDevice;
        }
      }
      
      // Update config if available
      if (config.value) {
        if (inputDevice !== undefined) {
          config.value.audio.input_device = inputDevice;
        }
        if (outputDevice !== undefined) {
          config.value.audio.output_device = outputDevice;
        }
      }
    } catch (err) {
      error.value = err instanceof Error ? err.message : "Failed to set audio device";
      throw err;
    } finally {
      loading.value = false;
    }
  };

  const loadAudioLevels = async () => {
    try {
      audioLevels.value = await tauriApi.getAudioLevels();
    } catch (err) {
      console.error("Failed to load audio levels:", err);
    }
  };

  const updateUiConfig = (uiConfig: AppConfig["ui"]) => {
    if (config.value) {
      config.value.ui = uiConfig;
    }
  };

  const updateAudioConfig = (audioConfig: AppConfig["audio"]) => {
    if (config.value) {
      config.value.audio = audioConfig;
    }
  };

  const exportConfig = async (): Promise<string> => {
    loading.value = true;
    error.value = null;
    
    try {
      return await tauriApi.exportConfig();
    } catch (err) {
      error.value = err instanceof Error ? err.message : "Failed to export config";
      throw err;
    } finally {
      loading.value = false;
    }
  };

  const importConfig = async (base64Data: string) => {
    loading.value = true;
    error.value = null;
    
    try {
      await tauriApi.importConfig(base64Data);
      // Reload config after import
      await loadConfig();
    } catch (err) {
      error.value = err instanceof Error ? err.message : "Failed to import config";
      throw err;
    } finally {
      loading.value = false;
    }
  };

  const checkConfigExists = async (): Promise<boolean> => {
    try {
      return await tauriApi.configExists();
    } catch (err) {
      console.error("Failed to check config existence:", err);
      return false;
    }
  };

  const clearError = () => {
    error.value = null;
  };

  return {
    // State
    config,
    audioDevices,
    audioLevels,
    loading,
    error,
    
    // Actions
    loadConfig,
    saveConfig,
    exportConfig,
    importConfig,
    checkConfigExists,
    loadAudioDevices,
    setAudioDevice,
    loadAudioLevels,
    updateUiConfig,
    updateAudioConfig,
    clearError,
  };
});